#!/bin/bash

. /dbld/functions.sh
DBLD_DIR=/dbld

DNF_INSTALL="dnf install -y"
APT_INSTALL="apt-get install -y --no-install-recommends"
ZYPPER_INSTALL="zypper -n install"

set -e
set -x

function hashfile() {
    FILE="$1"
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "${FILE}" | awk '{print $1}'
    elif command -v shasum >/dev/null 2>&1; then
        shasum -a 256 "${FILE}" | awk '{print $1}'
    else
        echo "Do not know how to create a file hash (no sha256sum, shasum found)!"
        exit 1
    fi
}

function update_packages() {
    case "${OS_DISTRIBUTION}" in
        debian|ubuntu)
            if [ "$JENKINS_URL" = "https://ci.syslog-ng.com/" ]; then
                # we are running under the ci.syslog-ng.com thus AWS. Use their
                # Ubuntu mirror, instead of spamming the real Ubuntu mirrors, as
                # they are really aggressive, when it comes to banning IPs over
                # hammering s of 2025.06.02.
                sed -i -e 's,http://\(archive\|security\).ubuntu.com,http://eu-west-1.ec2.archive.ubuntu.com,' /etc/apt/sources.list
                if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
                    sed -i -e 's,http://\(archive\|security\).ubuntu.com,http://eu-west-1.ec2.archive.ubuntu.com,' /etc/apt/sources.list.d/ubuntu.sources
                fi
            elif [ "$JENKINS_URL" = "github-hosted" ]; then
                # we are running under GitHub's env, thus we can use Microsoft's
                # Azure specific Ubuntu mirror. Yes, it's a dirty hack, I know ...
                sed -i -e 's,http://\(archive\|security\).ubuntu.com,http://azure.archive.ubuntu.com,' /etc/apt/sources.list
                if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
                    sed -i -e 's,http://\(archive\|security\).ubuntu.com,http://azure.archive.ubuntu.com,' /etc/apt/sources.list.d/ubuntu.sources
                fi
            fi
            apt-get update
            apt-get upgrade -y

            apt-get install -y curl
            curl -s "https://checkip.amazonaws.com"
            curl -s "http://whatismyip.akamai.com"

            ;;
        fedora|rhel|rocky|centos|almalinux)
            dnf upgrade -y
            ;;
        opensuse)
            zypper -n dist-upgrade
            zypper -n update
            ;;
    esac
}

function workaround_rpm_repos() {
    MIRROR_URL='https://ftp.halifax.rwth-aachen.de/fedora/linux'
    case "${OS_DISTRIBUTION}" in
        fedora)
            # Workaround for often getting 503 from mirrors.fedoraproject.org.
            sed -i -e "/baseurl/c\baseurl=${MIRROR_URL}/releases/\$releasever/Everything/\$basearch/os/" /etc/yum.repos.d/fedora.repo
            sed -i -e "/baseurl/c\baseurl=${MIRROR_URL}/updates/\$releasever/Everything/\$basearch/" /etc/yum.repos.d/fedora-updates.repo
            # we don't need h264 codecs
            sed -i -e "/enabled/c\enabled=0" /etc/yum.repos.d/fedora-cisco-openh264.repo
            ;;
    esac
}

# this function is run first and is responsible for installing stuff that is
# needed by this script _before_ installing packages from packages.manifest.
#
# NOTE: If at all possible don't put anything here.
function install_dbld_dependencies()
{
    case "${OS_DISTRIBUTION}" in
        debian|ubuntu)
            $APT_INSTALL curl gnupg2
            ;;
        centos|almalinux|fedora|rhel|rocky)
            $DNF_INSTALL dnf-plugins-core sudo
            ;;
        opensuse)
            $ZYPPER_INSTALL sudo
            ;;
    esac
}

function download_target()
{
    TARGET=$1
    OUTPUT=$2
    FALLBACK_PATH=$3
    HASH=$4

    # NOTE: Any new fallback packages must be uploaded to this repo, do not forget to maintain if needed!
    #       Keep it version organized!
    OSE_GIT_DOWNLOAD_REPO="https://github.com/syslog-ng/syslog-ng-deps/raw/refs/heads/main"

    if ! curl --location --insecure --fail "$TARGET" --output "$OUTPUT"; then
        if [ -n "$FALLBACK_PATH" ]; then
            FALLBACK_URL="${OSE_GIT_DOWNLOAD_REPO}/${FALLBACK_PATH}"
            echo "Primary download failed, trying fallback: $FALLBACK_URL"
            curl --location --insecure --fail "$FALLBACK_URL" --output "$OUTPUT"
        else
            echo "Download failed and no fallback specified."
            return 1
        fi
    fi
    CURR_HASH=$(hashfile "${OUTPUT}")
    if [ "${HASH}" = "${CURR_HASH}" ]; then
        echo "Downloaded file hash matches"
    else
        echo "Downloaded file hash does not match"
        return 2
    fi
}

function install_criterion() {
    CRITERION_VERSION=2.3.3
    HASH="8c85e1fcdb9a39b82bee50394bedfe74a0c839ffff129ddfc6fb73b11adafa29"

    download_target "https://github.com/Snaipe/Criterion/releases/download/v${CRITERION_VERSION}/criterion-v${CRITERION_VERSION}.tar.bz2" /tmp/criterion.tar.bz2 criterion/${CRITERION_VERSION}/criterion.tar.bz2 "${HASH}"
    cd /tmp/
    tar xvf /tmp/criterion.tar.bz2
    cd /tmp/criterion-v${CRITERION_VERSION}
    cmake -DCMAKE_INSTALL_PREFIX=/usr .
    make install
    ldconfig
    rm -rf /tmp/criterion.tar.bz2 /tmp/criterion-v${CRITERION_VERSION}

}

function set_jvm_paths() {
    find / -name 'libjvm.so' | sed 's@/libjvm.so@@g' | tee --append /etc/ld.so.conf.d/openjdk-libjvm.conf
    ldconfig
}

function install_gradle {
    GRADLE_VERSION=4.10
    HASH="248cfd92104ce12c5431ddb8309cf713fe58de8e330c63176543320022f59f18"

    download_target "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip" /tmp/gradle.zip gradle/${GRADLE_VERSION}/gradle.zip "${HASH}"
    mkdir -p /opt/gradle
    unzip -d /opt/gradle /tmp/gradle.zip
    rm -rf /tmp/gradle.zip
    ln -s /opt/gradle/gradle-${GRADLE_VERSION}/bin/gradle /usr/bin/gradle
    find / -name 'libjvm.so' | sed 's@/libjvm.so@@g' | tee --append /etc/ld.so.conf.d/openjdk-libjvm.conf
    ldconfig
}

function install_pip2 {
    PIP_VERSION=2.7
    HASH="40ee07eac6674b8d60fce2bbabc148cf0e2f1408c167683f110fd608b8d6f416"

    download_target "https://bootstrap.pypa.io/pip/${PIP_VERSION}/get-pip.py" get-pip.py pip/${PIP_VERSION}/get-pip.py "${HASH}"
    python2 get-pip.py
}

function install_bison_from_source {
    BISON_VERSION=3.7.6
    HASH="69dc0bb46ea8fc307d4ca1e0b61c8c355eb207d0b0c69f4f8462328e74d7b9ea"

    cd /tmp
    download_target https://ftp.gnu.org/gnu/bison/bison-${BISON_VERSION}.tar.gz /tmp/bison-${BISON_VERSION}.tar.gz bison/${BISON_VERSION}/bison.tar.gz "${HASH}"
    tar xvfz /tmp/bison-${BISON_VERSION}.tar.gz
    cd /tmp/bison-${BISON_VERSION}
    ./configure --prefix=/usr/local --disable-nls
    make && make install
}

function filter_packages_by_platform {
    FILENAME=$1
    local IMAGE_PLATFORM_BASE=$(image_platform_base)
    grep -v "#" ${FILENAME} | grep -e "${IMAGE_PLATFORM_BASE}" -e "${OS_DISTRIBUTION}[^-]" | cut -d"[" -f1
}

function filter_pip_packages_by_platform_and_python_version {
    FILENAME=$1
    PYTHON_VERSION=$2
    local IMAGE_PLATFORM_BASE=$(image_platform_base)
    grep -v "#" ${FILENAME} | grep -e "${IMAGE_PLATFORM_BASE}" -e "${OS_DISTRIBUTION}[^-]" | grep -e "${PYTHON_VERSION}" | cut -d"[" -f1
}

function add_copr_repo {

    # NOTE: we are removing dnf plugins after enabling copr as they
    # install a couple of Python dependencies which then conflict with our
    # PIP installation later.
    case "${OS_DISTRIBUTION}" in
        centos|almalinux)
            dnf copr enable -y czanik/syslog-ng-githead
            case "${OS_DISTRIBUTION_CODE_NAME}" in
                8)
                    dnf config-manager --set-enabled powertools
                    ;;
                9|stream9|stream10)
                    dnf config-manager --set-enabled crb
                    ;;
                esac
            ;;
        fedora)
            if [ "${OS_DISTRIBUTION_CODE_NAME}" = "rawhide" ]; then
                dnf5 install -y 'dnf5-command(copr)'
            fi
            dnf copr enable -y czanik/syslog-ng-githead
            ;;
        rocky)
            dnf config-manager --set-enabled crb
            ;;
        # rhel)
        #     dnf copr enable -y czanik/syslog-ng-githead
        #     ;;
    esac

    update_packages
}

function add_epel_repo {
    case "${OS_DISTRIBUTION}" in
        centos|almalinux-8|almalinux-9|rocky)
            $DNF_INSTALL epel-release
            ;;
        rhel|almalinux)
            # $DNF_INSTALL epel-release
            # $DNF_INSTALL epel-next-release
            curl -LO https://dl.fedoraproject.org/pub/epel/epel-release-latest-${OS_DISTRIBUTION_CODE_NAME}.noarch.rpm
            rpm -Uvh epel-release-latest-${OS_DISTRIBUTION_CODE_NAME}.noarch.rpm
            if curl -fL -o epel-next-release-latest-${OS_DISTRIBUTION_CODE_NAME}.noarch.rpm https://dl.fedoraproject.org/pub/epel/epel-next-release-latest-${OS_DISTRIBUTION_CODE_NAME}.noarch.rpm; then
                rpm -Uvh epel-next-release-latest-${OS_DISTRIBUTION_CODE_NAME}.noarch.rpm
            fi
            /usr/bin/crb enable
            ;;
    esac
}

function install_apt_packages {
    apt-get update -qq -o Acquire::CompressionTypes::Order::=gz
    filter_packages_by_platform $DBLD_DIR/packages.manifest | xargs -t $APT_INSTALL --yes
}

function install_debian_build_deps {
    DEBIAN_CONTROL_FILE="${DBLD_DIR}/extra-files/${IMAGE_PLATFORM}/packaging-debian-control"
    if ! [ -f ${DEBIAN_CONTROL_FILE} ]; then
        echo "install_debian_build_deps() called from dockerfile but without a Debian control file, make sure that control file is copied over to ${DEBIAN_CONTROL_FILE} by the prepare step"
        exit 1
    fi
    deb_run_build_command mk-build-deps -i ${DEBIAN_CONTROL_FILE} -t "apt-get -y -o Debug::pkgProblemResolver=yes --no-install-recommends"
}

function install_rpm_build_deps {
    RPM_SPEC_FILE="${DBLD_DIR}/extra-files/${IMAGE_PLATFORM}/syslog-ng.spec"
    if ! [ -f ${RPM_SPEC_FILE} ]; then
        echo "install_rpm_build_deps() called from dockerfile but without a syslog-ng.spec file, make sure that control file is copied over to ${RPM_SPEC_FILE} by the prepare step"
        exit 1
    fi

    case "${OS_DISTRIBUTION}" in
        fedora|rhel|almalinux|centos|rocky)
            rpm_run_build_command dnf builddep -y --allowerasing ${RPM_SPEC_FILE}
            ;;
        opensuse)
            # FIXME: add support for build-deps in opensuse once it is needed
            rpm_run_build_command zypper --build-deps-only ${RPM_SPEC_FILE}
            ;;
    esac
}

function install_dnf_packages {
    $DNF_INSTALL findutils
    filter_packages_by_platform $DBLD_DIR/packages.manifest | xargs $DNF_INSTALL
}

function install_zypper_packages {
    $ZYPPER_INSTALL findutils
    filter_packages_by_platform $DBLD_DIR/packages.manifest | xargs $ZYPPER_INSTALL
}

function install_pip_packages {
    local python_executables="python2 python3"
    for python_executable in ${python_executables}; do
        local pip_install="${python_executable} -m pip install --ignore-installed --no-cache-dir --upgrade"
        ${pip_install} "pip"
        ${pip_install} "setuptools<66.0"
        filter_pip_packages_by_platform_and_python_version $DBLD_DIR/pip_packages.manifest ${python_executable} | xargs ${pip_install}
    done
}

function install_lsb_release {
    apt-get update && $APT_INSTALL lsb-release
}

function enable_dbgsyms {
    install_lsb_release
    case "${OS_DISTRIBUTION}" in
        ubuntu)
            echo "deb http://ddebs.ubuntu.com ${OS_DISTRIBUTION_CODE_NAME} main restricted universe multiverse" | tee -a /etc/apt/sources.list.d/ddebs.list
            echo "deb http://ddebs.ubuntu.com ${OS_DISTRIBUTION_CODE_NAME}-updates main restricted universe multiverse" | tee -a /etc/apt/sources.list.d/ddebs.list
            apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 428D7C01 C8CAB6595FDFF622
            ;;
        debian)
            echo "deb http://deb.debian.org/debian-debug/ ${OS_DISTRIBUTION_CODE_NAME}-debug main" | tee -a /etc/apt/sources.list
            echo "deb http://deb.debian.org/debian-debug/ ${OS_DISTRIBUTION_CODE_NAME}-proposed-updates-debug main" | tee -a /etc/apt/sources.list
            ;;
    esac
}

function install_perf {
    case "${OS_DISTRIBUTION}" in
        ubuntu)
            apt-cache search linux-tools | grep 'linux-tools-.*-generic' | cut -d" " -f1 | tail -n1 | cut -d"-" -f1-4 | xargs $APT_INSTALL
            ;;
    esac
}


# DO NOT REMOVE!
"$@"
